import 'dart:developer';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/common/DemoLocalizations.dart';
import 'package:flutter_app/common/Git.dart';
import 'package:flutter_app/common/Global.dart';
import 'package:flutter_app/common/ProfileChangeNotifier.dart';
import 'package:flutter_app/models/user.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';

class LoginRoute extends StatefulWidget {
  @override
  _LoginRouteState createState() => _LoginRouteState();
}

class _LoginRouteState extends State<LoginRoute> {
  TextEditingController userNameController = new TextEditingController();
  TextEditingController pwdController = new TextEditingController();
  bool pwdVisible = false;

  GlobalKey _globalKey = new GlobalKey();
  bool nameAutoFocus = true;

  @override
  void initState() {
    // 自动填充上次登录的用户名，填充后将焦点定位到密码输入框
    userNameController.text = Global.profile.lastLogin;
    if (userNameController.text != null) {
      nameAutoFocus = false;
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var gm = DemoLocalizations.of(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(gm.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _globalKey,
          autovalidateMode: AutovalidateMode.always,
          child: Column(
            children: <Widget>[
              TextFormField(
                autofocus: nameAutoFocus,
                controller: userNameController,
                decoration: InputDecoration(
                    labelText: gm.title,
                    hintText: gm.title,
                    prefixIcon: Icon(Icons.verified_user)),
                validator: (v) {
                  return v.trim().isNotEmpty ? null : "用户名不能为空";
                },
              ),
              TextFormField(
                controller: pwdController,
                autofocus: !nameAutoFocus,
                decoration: InputDecoration(
                    labelText: "密码",
                    hintText: "请输入密码",
                    prefixIcon: Icon(Icons.content_paste_sharp),
                    suffixIcon: IconButton(
                      icon: Icon(
                        pwdVisible ? Icons.visibility_off : Icons.visibility,
                      ),
                      onPressed: () {
                        setState(() {
                          pwdVisible = !pwdVisible;
                        });
                      },
                    )),
                validator: (v) {
                  return v.trim().isNotEmpty ? null : "密码不能为空";
                },
              ),
              Padding(
                padding: const EdgeInsets.only(top: 25.0),
                child: ConstrainedBox(
                  constraints: BoxConstraints.expand(height: 55.0),
                  child: RaisedButton(
                    color: Theme.of(context).primaryColor,
                    textColor: Colors.white,
                    child: Text("登录"),
                    onPressed: _onLogin,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _onLogin() async {
    // 提交前，先验证各个表单字段是否合法
    if ((_globalKey.currentState as FormState).validate()) {
      showLoading(context);
      User user;
      try {
        user = await Git(context)
            .login(userNameController.text, pwdController.text);
        // 因为登录页返回后，首页会build，所以我们传false，更新user后不触发更新
        Provider.of<UserModel>(context, listen: null).user = user;
      } catch (e) {
        //登录失败则提示
        print("e.response?.statusCode =${e.response?.statusCode}");
      } finally {
        print("user=$user");
        Navigator.pop(context);
      }
      print("user=$user");
      if (null != user) {
        Navigator.pop(context);
      }
    }
  }

  void showLoading(BuildContext context) {}
}
